import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { createHash } from 'crypto';
import { GenerationCache } from '../schemas/generation-cache.schema';
import { Workflow, WorkflowParams } from '../interfaces/workflow.interface';

@Injectable()
export class CacheService {
    private readonly cacheDuration = 24 * 60 * 60 * 1000; // 24小时

    constructor(
        @InjectModel(GenerationCache.name)
        private cacheModel: Model<GenerationCache>
    ) { }

    private generateCacheKey(workflow: Workflow, params: WorkflowParams): string {
        const data = JSON.stringify({ workflow, params });
        return createHash('md5').update(data).digest('hex');
    }

    async getCachedResult(workflow: Workflow, params: WorkflowParams): Promise<string | null> {
        const cacheKey = this.generateCacheKey(workflow, params);
        const cached = await this.cacheModel.findOne({
            key: cacheKey,
            createdAt: { $gt: new Date(Date.now() - this.cacheDuration) }
        });

        return cached ? cached.imageUrl : null;
    }

    async cacheResult(workflow: Workflow, params: WorkflowParams, imageUrl: string): Promise<void> {
        const cacheKey = this.generateCacheKey(workflow, params);
        await this.cacheModel.create({
            key: cacheKey,
            workflow,
            params,
            imageUrl,
            createdAt: new Date()
        });
    }

    async clearExpiredCache(): Promise<void> {
        await this.cacheModel.deleteMany({
            createdAt: { $lt: new Date(Date.now() - this.cacheDuration) }
        });
    }
} 